package com.ruoyi.manage.controller;

import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.manage.domain.AttAttendanceSummary;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.manage.domain.AttAttendance;
import com.ruoyi.manage.service.IAttAttendanceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 员工考勤记录Controller
 * 
 * @author cf
 * @date 2025-06-03
 */
@RestController
@RequestMapping("/manage/attendance")
public class AttAttendanceController extends BaseController {
    @Autowired
    private IAttAttendanceService attAttendanceService;

    /**
     * 查询员工考勤记录列表
     */
//    @PreAuthorize("@ss.hasPermi('manage:attendance:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(AttAttendance attAttendance)
//    {
//        startPage();
//        List<AttAttendance> list = attAttendanceService.selectAttAttendanceList(attAttendance);
//        return getDataTable(list);
//    }
    /**
     * 查询员工考勤记录列表（支持周期性查询）
     */
//    @PreAuthorize("@ss.hasPermi('manage:attendance:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(AttAttendance attAttendance,
//                              @RequestParam(required = false) String type,
//                              @RequestParam(required = false) String dateStr) {
//
//        // 如果没有传 type，则走原始逻辑
//        if (type == null || type.isEmpty()) {
//            startPage();
//            List<AttAttendance> list = attAttendanceService.selectAttAttendanceList(attAttendance);
//            return getDataTable(list);
//        }
//
//        LocalDate today = LocalDate.now();
//        int currentYear = today.getYear();
//
//        // 自动补全 dateStr
//        if (dateStr == null || dateStr.isEmpty()) {
//            switch (type) {
//                case "day":
//                    dateStr = today.format(DateTimeFormatter.ISO_DATE); // 2025-06-11
//                    break;
//                case "week":
//                    WeekFields weekFields = WeekFields.of(Locale.getDefault());
//                    int weekOfYear = today.get(weekFields.weekOfWeekBasedYear());
//                    dateStr = currentYear + "-W" + String.format("%02d", weekOfYear);
//                    break;
//                case "month":
//                    int month = today.getMonthValue();
//                    dateStr = currentYear + "-" + String.format("%02d", month);
//                    break;
//                case "quarter":
//                    int quarter = (today.getMonthValue() - 1) / 3 + 1;
//                    dateStr = currentYear + "-Q" + quarter;
//                    break;
//                case "year":
//                    dateStr = String.valueOf(currentYear);
//                    break;
//                default:
//                    dateStr = String.valueOf(currentYear);
//            }
//        }
//
//        if ("day".equalsIgnoreCase(type)) {
//            Date date = Date.from(LocalDate.parse(dateStr).atStartOfDay(ZoneId.systemDefault()).toInstant());
//            attAttendance.setAttendanceDate(date); // 设置日期过滤
//            startPage();
//            List<AttAttendance> list = attAttendanceService.selectAttAttendanceList(attAttendance);
//            return getDataTable(list);
//        } else {
//            List<AttAttendanceSummary> summaryList = attAttendanceService.selectAttendanceSummaryByPeriod(type, dateStr);
//            return getDataTable(summaryList);
//        }
//    }
    @PreAuthorize("@ss.hasPermi('manage:attendance:list')")
    @GetMapping("/countLateToday")
    public AjaxResult countLateToday() {
        return AjaxResult.success(attAttendanceService.countLateToday());
    }

    @PreAuthorize("@ss.hasPermi('manage:attendance:list')")
    @GetMapping("/countEarlyLeaveToday")
    public AjaxResult countEarlyLeaveToday() {
        return AjaxResult.success(attAttendanceService.countEarlyLeaveToday());
    }

    @PreAuthorize("@ss.hasPermi('manage:attendance:list')")
    @GetMapping("/countAbsentToday")
    public AjaxResult countAbsentToday() {
        return AjaxResult.success(attAttendanceService.countAbsentToday());
    }

    @PreAuthorize("@ss.hasPermi('manage:attendance:list')")
    @GetMapping("/countLeaveToday")
    public AjaxResult countLeaveToday() {
        return AjaxResult.success(attAttendanceService.countLeaveToday());
    }


    /**
     * 查询员工考勤记录列表（支持周期性查询）
     */
    @PreAuthorize("@ss.hasPermi('manage:attendance:list')")
    @GetMapping("/list")
    public TableDataInfo list(AttAttendance attAttendance,
                              @RequestParam(required = false) String type,
                              @RequestParam(required = false) String dateStr,
                              @RequestParam(required = false) Date beginTime,
                              @RequestParam(required = false) Date endTime) {
        // 原始逻辑：未传type时查询原始数据
        if (type == null || type.isEmpty()) {
            startPage();
            List<AttAttendance> list = attAttendanceService.selectAttAttendanceList(attAttendance);
            return getDataTable(list);
        }

        LocalDate today = LocalDate.now();
        int currentYear = today.getYear();

        // 自动补全dateStr（确保非空）
        if (dateStr == null || dateStr.isEmpty()) {
            switch (type.toLowerCase()) {
                case "day":
                    dateStr = today.format(DateTimeFormatter.ISO_DATE);
                    break;
                case "week":
                    // 计算当前周的周一（以中国Locale的周一开始）
                    dateStr = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).format(DateTimeFormatter.ISO_DATE);
                    break;
                case "month":
                    dateStr = today.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                    break;
                case "quarter":
                    int quarter = (today.getMonthValue() - 1) / 3 + 1;
                    dateStr = currentYear + "-Q" + quarter;
                    break;
                case "year":
                    dateStr = String.valueOf(currentYear);
                    break;
                default:
                    dateStr = String.valueOf(currentYear);
            }
        }

        // 自动生成时间范围（beginTime和endTime均为空时）
        Date startDate = beginTime;
        Date endDate = endTime;
        if (startDate == null && endDate == null) {
            try {
                LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE); // 统一解析为LocalDate
                switch (type.toLowerCase()) {
                    case "day":
                        startDate = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        endDate = Date.from(date.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant()); // 包含当天23:59:59
                        break;
                    case "week":
                        // 计算周一起始和周日结束
                        LocalDate weekStart = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                        LocalDate weekEnd = weekStart.plusDays(6);
                        startDate = Date.from(weekStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        endDate = Date.from(weekEnd.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
                        break;
                    case "month":
                        LocalDate monthStart = date.withDayOfMonth(1);
                        LocalDate monthEnd = date.with(TemporalAdjusters.lastDayOfMonth());
                        startDate = Date.from(monthStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        endDate = Date.from(monthEnd.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
                        break;
                    case "quarter":
                        int qMonth = (Integer.parseInt(dateStr.split("-Q")[1]) - 1) * 3 + 1;
                        LocalDate quarterStart = LocalDate.of(date.getYear(), qMonth, 1);
                        LocalDate quarterEnd = LocalDate.of(date.getYear(), qMonth + 2, 1).minusDays(1); // 季度最后一天
                        startDate = Date.from(quarterStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        endDate = Date.from(quarterEnd.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
                        break;
                    case "year":
                        LocalDate yearStart = LocalDate.of(date.getYear(), 1, 1);
                        LocalDate yearEnd = LocalDate.of(date.getYear(), 12, 31);
                        startDate = Date.from(yearStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        endDate = Date.from(yearEnd.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
                        break;
                }
            } catch (Exception e) {
                logger.error("自动生成时间范围失败，dateStr={}, type={}", dateStr, type, e);
            }
        }

        // 处理日查询（原始逻辑）
        if ("day".equalsIgnoreCase(type)) {
            try {
                LocalDate dayDate = LocalDate.parse(dateStr);
                attAttendance.setAttendanceDate(Date.from(dayDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
            } catch (Exception e) {
                logger.error("解析日查询日期失败，dateStr={}", dateStr, e);
            }
            startPage();
            List<AttAttendance> list = attAttendanceService.selectAttAttendanceList(attAttendance);
            return getDataTable(list);
        } else {
            // 调用统计接口，传递类型、dateStr和计算好的时间范围
            List<AttAttendanceSummary> summaryList = attAttendanceService.selectAttendanceSummaryByPeriod(
                    type,
                    dateStr,
                    startDate,
                    endDate,
                    null
            );
            return getDataTable(summaryList);
        }
    }

    @PreAuthorize("@ss.hasPermi('manage:attendance:list')")
    @GetMapping("/details")
    public TableDataInfo details(@RequestParam Long staffId,
                                 @RequestParam(required = false) Date beginTime,
                                 @RequestParam(required = false) Date endTime) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String beginTimeString = beginTime != null ? sdf.format(beginTime) : null;
        String endTimeString = endTime != null ? sdf.format(endTime) : null;

        List<AttAttendance> attAttendanceList = attAttendanceService.selectAttAttendanceByDateRange(staffId, beginTimeString, endTimeString);
        return getDataTable(attAttendanceList);
    }


    /**
     * 根据周字符串获取该周的周一日期
     * 示例输入: "2025-W22"
     * 返回: 该周的周一日期
     */
    public static Date getMondayOfWeek(String weekStr) {
        if (weekStr == null || !weekStr.matches("\\d{4}-W\\d{1,2}")) {
            throw new IllegalArgumentException("周格式不正确，应为YYYY-Www，如2025-W22");
        }

        String[] parts = weekStr.split("-W");
        int year = Integer.parseInt(parts[0]);
        int week = Integer.parseInt(parts[1]);

        LocalDate firstDayOfYear = LocalDate.of(year, 1, 1);
        LocalDate firstMonday = firstDayOfYear.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate monday = firstMonday.plusWeeks(week - 1);

        return Date.from(monday.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static Date getSundayOfWeek(String weekStr) {
        LocalDate monday = getMondayOfWeek(weekStr).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate sunday = monday.plusDays(6);
        return Date.from(sunday.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }






    /**
     * 导出员工考勤记录列表
     */
    @PreAuthorize("@ss.hasPermi('manage:attendance:export')")
    @Log(title = "员工考勤记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(required = false) AttAttendance attAttendance,
                       @RequestParam(required = false)String type,
                       @RequestParam(required = false) Date beginTime,
                       @RequestParam(required = false) Date endTime) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 如果 beginTime 或 endTime 为空，则默认为当月1号到当前日期
        if (beginTime == null || endTime == null) {
            LocalDate now = LocalDate.now();
            LocalDate firstDayOfMonth = now.withDayOfMonth(1);

            beginTime = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
            endTime = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
        }

        if (attAttendance == null) {
            attAttendance = new AttAttendance();
        }

        if(type == null)
        {
            List<AttAttendance> list = attAttendanceService.selectAttAttendanceByDateRange(
                    attAttendance.getStaffId(),
                    sdf.format(beginTime),
                    sdf.format(endTime)
            );
            ExcelUtil<AttAttendance> util = new ExcelUtil<>(AttAttendance.class);
            util.exportExcel(response, list, "员工考勤记录数据");
        }
        else
        {
            List<AttAttendanceSummary> summaryList = attAttendanceService.selectAttendanceSummaryByPeriod(
                    type,
                    null,
                    beginTime,
                    endTime,
                    attAttendance.getStaffId()
            );
            ExcelUtil<AttAttendanceSummary> util = new ExcelUtil<>(AttAttendanceSummary.class);
            logger.info("summaryList：{}", summaryList);
            util.exportExcel(response, summaryList, "员工考勤记录数据总结");
        }




    }


    /**
     * 获取员工考勤记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:attendance:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(attAttendanceService.selectAttAttendanceById(id));
    }

    /**
     * 新增员工考勤记录
     */
    @PreAuthorize("@ss.hasPermi('manage:attendance:add')")
    @Log(title = "员工考勤记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AttAttendance attAttendance)
    {
        return toAjax(attAttendanceService.insertAttAttendance(attAttendance));
    }

    /**
     * 修改员工考勤记录
     */
    @PreAuthorize("@ss.hasPermi('manage:attendance:edit')")
    @Log(title = "员工考勤记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AttAttendance attAttendance)
    {
        return toAjax(attAttendanceService.updateAttAttendance(attAttendance));
    }

    /**
     * 删除员工考勤记录
     */
    @PreAuthorize("@ss.hasPermi('manage:attendance:remove')")
    @Log(title = "员工考勤记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(attAttendanceService.deleteAttAttendanceByIds(ids));
    }
}
